<template>
  <PageContainer 
    :show-nav-bar="true"
    :show-back="false"
    :title="h5Title"
    :title-color="h5TitleColor"
    :background-color="'#ffffff'"
  >
    <!-- 头部背景区域 -->
    <view class="header-bg" :style="{ backgroundImage: `url(${backgroundImageUrl})` }">
      <!-- 关闭按钮 -->
      <view class="close-btn" @click="handleClose">
        <image class="close-icon" :src="getImageUrl('/static/Images/common/Guanbihei.png')" mode="aspectFit"></image>
      </view>
      <!-- 欢迎文字 -->
      <view class="welcome-section">
        <text class="welcome-text">您好，</text>
        <text class="welcome-text">欢迎来到充值平台</text>
      </view>
    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 手机号输入框 -->
      <view class="input-group">
        <input 
          class="input-field" 
          type="number" 
          placeholder="请输入手机号" 
          v-model="phoneNumber"
          maxlength="11"
        />
      </view>
      
      <!-- 验证码输入框 -->
      <view class="input-group verification-group">
        <input 
          class="input-field verification-input" 
          type="number" 
          placeholder="请输入验证码" 
          v-model="verificationCode"
          maxlength="4"
        />
        <view class="send-code-btn" @click="sendVerificationCode" :class="{ disabled: countdown > 0 }">
          <text class="send-code-text">{{ countdown > 0 ? `${countdown}s` : '发送验证码' }}</text>
        </view>
      </view>
      
      <!-- 邀请码输入框 -->
      <view class="input-group">
        <input 
          class="input-field" 
          type="text" 
          placeholder="请输入邀请码（选填）" 
          v-model="inviteCode"
          maxlength="20"
        />
      </view>
      
      <!-- 同意条款 -->
      <view class="agreement-section">
        <view class="checkbox-wrapper" @click="toggleAgreement">
          <view class="checkbox" :class="{ checked: isAgreed }">
            <view class="checkbox-inner" v-if="isAgreed"></view>
          </view>
          <text class="agreement-text">我已阅读并同意</text>
          <text class="agreement-link" @click.stop="showServiceAgreement">服务协议</text>
          <text class="agreement-text">、</text>
          <text class="agreement-link" @click.stop="showPrivacyPolicy">隐私权政策</text>
        </view>
      </view>
      <!-- 注册提示 -->
      <view class="register-tip">
        <text class="register-text">已经有账号？</text>
        <text class="register-link" @click="goToLogin">立即登录</text>
      </view>
      <!-- 登录按钮 -->
      <view class="login-btn" @click="handleLogin">
        <text class="login-btn-text">注册</text>
      </view>
    </view>
    
    <!-- 第三方登录 -->
    <view class="third-party-section">
      <text class="third-party-title">使用第三方账号登录</text>
      <view class="third-party-buttons">
        <view class="third-party-btn" @click="handleWechatLogin">
          <image class="third-party-icon" src="/static/Images/common/Wechat.png" mode="aspectFit"></image>
        </view>
        <view class="third-party-btn" @click="handleQQLogin">
          <image class="third-party-icon" src="/static/Images/common/QQ.png" mode="aspectFit"></image>
        </view>
      </view>
    </view>
    </view>  
  </PageContainer>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { smsApi, userApi } from '@/utils/api';
import { getImageUrl } from '@/config/api';
import { validatePhone, validateCode } from '@/utils/validate';
import { userStorage } from '@/utils/storage';

// 响应式数据
const phoneNumber = ref('');
const verificationCode = ref('');
const inviteCode = ref('');
const isAgreed = ref(false);
const countdown = ref(0);
let countdownTimer = null;

// 页面加载时获取URL中的邀请码
onMounted(() => {
  // 获取URL参数中的邀请码
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};
  
  if (options.sno) {
    inviteCode.value = options.sno;
  }
});

// 计算属性
const canLogin = computed(() => {
  return validatePhone(phoneNumber.value) && 
         /^\d{4}$/.test(verificationCode.value) && 
         isAgreed.value;
});

// H5平台标题显示
const h5Title = computed(() => {
  // 使用运行时平台检测
  const platform = uni.getSystemInfoSync().platform;
  const isH5 = platform === 'devtools' || typeof window !== 'undefined';
  return isH5 ? '注册' : '';
});

const h5TitleColor = computed(() => {
  // 使用运行时平台检测
  const platform = uni.getSystemInfoSync().platform;
  const isH5 = platform === 'devtools' || typeof window !== 'undefined';
  return isH5 ? '#000000' : '';
});

// 背景图片URL
const backgroundImageUrl = computed(() => {
  return getImageUrl('/static/Images/common/Loginbj.png');
});

// 关闭页面
const handleClose = () => {
  uni.navigateBack();
};

// 跳转到登录页面
const goToLogin = () => {
  uni.navigateTo({
    url: '/pages/login/login'
  });
};

// 切换同意状态
const toggleAgreement = () => {
  isAgreed.value = !isAgreed.value;
};

// 发送验证码
const sendVerificationCode = async () => {
  if (countdown.value > 0) return;
  
  if (!validatePhone(phoneNumber.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 显示加载状态
    uni.showLoading({
      title: '发送中...'
    });
    
    // 调用发送验证码API
    const response = await smsApi.sendCode(phoneNumber.value);
    
    uni.hideLoading();
    
    // 发送成功，开始倒计时
    countdown.value = 60;
    countdownTimer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer);
      }
    }, 1000);
    
    uni.showToast({
      title: response.msg || '验证码已发送',
      icon: 'success'
    });
    
  } catch (error) {
    uni.hideLoading();
    console.error('发送验证码失败:', error);
    uni.showToast({
      title: error.message || '发送失败，请重试',
      icon: 'none'
    });
  }
};

// 登录处理 -> 改为注册处理
const handleLogin = async () => {
  // 点击时进行校验并给出提示，而不是禁用按钮
  if (!validatePhone(phoneNumber.value)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
    return;
  }
  // 验证码改为4位数字校验
  if (!/^\d{4}$/.test(verificationCode.value)) {
    uni.showToast({ title: '请输入验证码！', icon: 'none' });
    return;
  }
  if (!isAgreed.value) {
    uni.showToast({ title: '请先阅读并同意服务协议与隐私权政策', icon: 'none' });
    return;
  }

  try {
    uni.showLoading({ title: '注册中...' });
    // 调用注册API
    const response = await userApi.register({
      mobile: phoneNumber.value,
      msgCode: verificationCode.value,
      sno: inviteCode.value,
      pwd: '123456'
    });

    uni.hideLoading();

    if (response && (response.success || response.code === 200 || response.code === 1)) {
      uni.showToast({ title: '注册成功', icon: 'success' });
      // 注册成功后跳转首页或执行登录逻辑
      setTimeout(() => {
        uni.reLaunch({ url: '/pages/index/index' });
      }, 1200);
    } else {
      throw new Error(response?.msg || '注册失败');
    }
  } catch (error) {
    uni.hideLoading();
    console.error('注册失败:', error);
    uni.showToast({ title: error.message || '注册失败，请重试', icon: 'none' });
  }
};

// 微信登录
const handleWechatLogin = () => {
  uni.showToast({
    title: '微信登录功能开发中',
    icon: 'none'
  });
};

// QQ登录
const handleQQLogin = () => {
  uni.showToast({
    title: 'QQ登录功能开发中',
    icon: 'none'
  });
};

// 显示服务协议
const showServiceAgreement = () => {
  uni.navigateTo({
    url: '/pages/agreement/service'
  });
};

// 显示隐私政策
const showPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/pages/agreement/privacy'
  });
};

// 页面卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style lang="scss" scoped>
/* 头部背景区域 */
.header-bg {
  position: relative;
  overflow: hidden;
  background-size: 120% 100%;
  background-position: center;
  background-repeat: no-repeat;
}

/* 关闭按钮 */
.close-btn {
  position: absolute;
  width: 20rpx;
  height: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  left: 1rem;
  top: 1rem;
}

.close-icon {
  width: 40rpx;
  height: 40rpx;
}

/* 欢迎区域 */
.welcome-section {
  padding: 3.8rem 1.85rem;
  margin-top: 5rem;
}

.welcome-text {
  display: block;
  font-size: 48rpx;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
}

/* 表单区域 */
.form-section {
  flex: 1;
  padding: 0 60rpx;
}

.input-group {
  margin-bottom: 40rpx;
  position: relative;
}

.input-field {
  height: 100rpx;
  background-color: #f0f0f0;
  border-radius: 12rpx;
  padding: 0 30rpx;
  font-size: 32rpx;
  color: #333;
  border: none;
  outline: none;
}

.input-field::placeholder {
  color: #999;
}

/* 验证码输入组 */
.verification-group {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.verification-input {
  flex: 1;
}

.send-code-btn {
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #ff4757;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 200rpx;
}

.send-code-btn.disabled {
  background-color: #ccc;
}

.send-code-text {
  font-size: 28rpx;
  color: #fff;
  font-weight: 500;
}

/* 同意条款 */
.agreement-section {
  margin: 60rpx 0 80rpx;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.checkbox {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #ddd;
  border-radius: 50%;
  margin-right: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.checkbox.checked {
  border-color: #ff4757;
  background-color: #ff4757;
}

.checkbox-inner {
  width: 12rpx;
  height: 12rpx;
  background-color: #fff;
  border-radius: 50%;
}

.agreement-text {
  font-size: 26rpx;
  color: #666;
}

.agreement-link {
  font-size: 26rpx;
  color: #ff4757;
  text-decoration: underline;
}

/* 注册提示 */
.register-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
}

.register-text {
  font-size: 28rpx;
  color: #666;
  margin-right: 8rpx;
}

.register-link {
  font-size: 28rpx;
  color: #ff4757;
  font-weight: 500;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 100rpx;
  background-color: #ff4757;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 60rpx;
}

.login-btn.disabled {
  background-color: #ccc;
}

.login-btn-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: 500;
}

/* 第三方登录 */
.third-party-section {
  padding: 0 60rpx 60rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.third-party-title {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.third-party-buttons {
  display: flex;
  gap: 60rpx;
}

.third-party-btn {
  width: 100rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.third-party-icon {
  width: 80rpx;
  height: 80rpx;
}


</style>